<template>
    <div>
        <el-card>
            <el-form :model="queryForm" :inline="true">
                <el-form-item label="章节名">
                    <el-input type="text" placeholder="请输入章节名" v-model="queryForm.mediaTitle" size="small" ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="small" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 数据卡片 -->
        <el-card class="mt12" style="margin-top: 10px">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd()">新增</el-button>
                    <el-button size="small" icon="el-icon-delete" type="danger" plain @click="handleBatchDelete()">删除</el-button>
                </div>
            </div>
            <!-- 数据表格 -->
            <el-table
            :data="userList"
            v-loading="loading"
            border
            fit
            :header-cell-style="{background:'#f8f8f9',color:'#5a516e',padding:'10px 0px'}"
            :cell-style="{padding:'5px 0px'}"
            @selection-change="handleSelectionChange"
            style="margin: 10px 0">
                <el-table-column type="selection" align="center" width="50px" :selectable="checkSelectable"></el-table-column>
                <el-table-column label="封 面" align="center" width="80">
                    <template slot-scope="scope">
                        <div style="display: flex; justify-content: center;">
                            <el-image 
                                :src="'/imgs/cover' + scope.row.coverPath"
                                style="width: 80px; height: 80px"
                                fit="contain" 
                            ></el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="小说名"  align="center" width="240">
                    <template slot-scope="scope">
                    {{ scope.row.mediaTitle }}
                    </template>
                </el-table-column>
                <el-table-column label="作 者"  align="center" width="240">
                    <template slot-scope="scope">
                    {{ scope.row.mediaAuthor }}
                    </template>
                </el-table-column>
                <el-table-column label="上传者昵称"  align="center" width="240">
                    <template slot-scope="scope">
                    {{ scope.row.nickname }}
                    </template>
                </el-table-column>
                <el-table-column label="章节名" align="center">
                    <template slot-scope="scope">
                    <span>{{ scope.row.mediaName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="小说简介" align="center">
                    <template slot-scope="scope">
                        <el-tooltip 
                            effect="dark" 
                            :content="scope.row.mediaInfo" 
                            placement="top"
                            >
                            <div class="text-ellipsis-multi">
                                {{ scope.row.mediaInfo }}
                            </div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操 作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                    :current-page="queryForm.pageNum" 
                    :page-size="queryForm.pageSize"
                    :total="total"
                    :page-sizes="[10,20,50,100]"
                    layout="total,sizes,prev,pager,next"
                    @current-change='handleCurrentChange'
                    @size-change='handleSizeChange'>
                </el-pagination>
        </el-card>
        <!-- 新增和编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="show"  width="42%">
            <el-form :model="submitForm" :inline="true" label-width="120px" :rules='rules' ref="submitForm">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="章节名" prop="mediaName">
                            <el-input type="text" placeholder="请输入章节名" v-model="submitForm.mediaName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上 传" prop="mediaPath">
                            <el-upload
                                action=/admin-api/file/upload/novel/
                                :data="{ userId: uploaderId}"
                                :on-success="handleSuccess" 
                                :headers="headers"
                                name="file"
                                :before-upload="beforeUpload"  
                                :on-remove="handleRemove"
                                :file-list="fileList"
                                :limit="1">
                                <el-button type="primary">点击上传</el-button>
                                <template #tip>
                                    <div class="el-upload__tip">支持TXT文件，且不超过500KB</div>
                                    <div v-if="novelUrl" class="uploaded-file-container">
                                        <div class="el-upload-list el-upload-list--text">
                                            <div class="el-upload-list__item is-success">
                                                <a class="el-upload-list__item-name" @click="downloadFile()">
                                                <i class="el-icon-document"></i>
                                                {{ getFileName(novelUrl) }}
                                                </a>
                                                <label class="el-upload-list__item-status-label">
                                                <i class="el-icon-upload-success el-icon-circle-check"></i>
                                                </label>
                                                <i class="el-icon-close" @click="handleRemove"></i>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="dialog-footer" slot="footer" style="margin-right:40px;">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { selectAll,getMedia,addMedia,updateMedia,deleteMedia,removeMediaFile } from '@/api/media'
    export default {
        name:'MediaNovel',
        data(){
            return{
                loading: true,
                userId:this.$Cookie.get("userId"),
                submitForm:{},
                title:"新增",
                show:false,
                total:120,
                queryForm:{
                    collectionId:this.$route.query.collectionId,
                    mediaType:0,
                    pageNum:1,
                    pageSize:10,
                    desc:"1"
                },
                selectList:[],
                userList:[],
                novelFileName:null,
                fileList:[],
                novelUrl:'',
                headers:{
                    Authorization: 'Bearer ' + this.$Cookie.get('login-token')
                },
                loadProgress: 0,
                progressStatus:null,
                progressStyle: "margin-top:5px;opacity: 0;",
                uploaderId: 100001,
                rules:{
                    mediaName:[
                        {required:true,message:'请输入章节名',trigger:'blur'},
                        {min:1,max:16,message:'长度必须在1-16之间',trigger:'blur'}
                    ],
                    mediaPath:[
                        {required:true,message:'请上传小说文件',trigger:'blur'}
                    ]    
                }
            }
        },
        //创建网页后查询调用数据
        created(){
            this.getList()
        },
        methods:{
            //调用接口提交数据 - 进行添加和编辑操作的弹窗
            handleSubmit(){
                this.submitForm.collectionId = this.$route.query.collectionId
                this.$refs['submitForm'].validate((valid)=>{
                    this.fileList = []
                    if(valid){
                        if(this.submitForm.id){
                            this.submitForm.uploaderId = this.uploaderId
                            this.submitForm.updateBy = this.$Cookie.get("username")
                            updateMedia(this.submitForm).then(res=>{
                                this.show = false
                                this.getList()
                                this.submitForm = {}
                            }).catch(err=>{
                                console.log(err)
                            })
                        }else{
                            this.submitForm.uploaderId = 100001
                            this.submitForm.createBy = this.$Cookie.get("username")
                            addMedia(this.submitForm).then(res=>{
                                this.show = false
                                this.getList()
                                this.submitForm = {}
                            }).catch(err=>{
                                console.log(err)
                            })
                        }
                        
                    }
                })
            },
            //重置搜索
            handleReset(){
                this.queryForm = {
                    collectionId:this.$route.query.collectionId,
                    mediaType:0,
                    pageNum:1,
                    pageSize:10,
                    desc:"1"
                }
                this.getList()
            },
            //按条件搜索
            handleSearch(){
                this.queryForm.collectionId = this.$route.query.collectionId
                this.queryForm.mediaType = 0
                this.queryForm.pageNum = 1
                this.queryForm.pageSize = 10
                this.queryForm.desc = "1"
                this.getList()
            },
            //修改每页大小
            handleSizeChange(pageSize){
                this.queryForm.pageSize = pageSize
                this.queryForm.pageNum = 1
                this.getList()
            },
            //当前页修改
            handleCurrentChange(pageNum){
                this.queryForm.pageNum = pageNum
                this.getList()
            },
            //调用接口分页查询用户数据
            getList(){
                this.loading = true
                selectAll(this.queryForm).then(res=>{
                    this.userList = res.data.records
                    this.total = res.data.total
                    this.loading = false
                }).catch(err=>{})
            },
            //删除 - 调用接口删除记录
            handleDelete(ids){
                this.$confirm("你确定删除id为"+ids+"的记录吗？","提示",{
                    cancelButtonText:"取消",
                    confirmButtonText:"确定",
                    type:"warning"
                }).then(()=>{
                    console.log("删除确认")
                    //调接口删除
                    deleteMedia(ids).then(res => {
                        //提示删除成功
                        this.$message("删除成功")
                        //刷新列表
                        this.getList()
                    }).catch(err=>{
                        console.log(err)
                    })
                }).catch(()=>{})
            },
            //添加 - 打开添加弹窗
            handleAdd(){
                this.show = true
                this.title = "新增"
                this.novelUrl = ''
                this.uploaderId = 100001
                this.submitForm = {
                    mediaPath:''
                }
                this.address={}
            },
            //取消 - 关闭弹窗
            handleCancel(){
                this.show = false
            },
            //编辑 - 打开编辑弹窗
            handleEdit(id){
                getMedia(id).then(res=>{
                    //调接口获取最新数据
                    this.title = "编辑"
                    this.show = true
                    this.submitForm = res.data
                    this.novelUrl = res.data.mediaPath
                    this.uploaderId = res.data.uploaderId
                }).catch(err=>{
                    console.log(err)
                })
                
            },
            //批量删除
            handleBatchDelete(){
                if(this.selectList){
                    let ids = this.selectList.map(o => {return o.id})
                    console.log('ids---------->',ids)
                    this.handleDelete(ids)
                }
            },
            //多选
            handleSelectionChange(val){
                this.selectList = val;
            },
            //选择时，如果为自己id则不能选中
            checkSelectable(row) {
                return row.id != this.userId
            },
            //上传校验
            beforeUpload(file) {
                const isAllowedType = file.type === 'text/plain' || file.name.endsWith('.txt')
                const isSizeValid = file.size / 1024 < 500  // 500KB限制
                if (!isAllowedType) {
                    this.$message.error('只能上传TXT格式!')
                }
                if (!isSizeValid) {
                    this.$message.error('文件大小不能超过500KB!')
                }
                return isAllowedType && isSizeValid  // 返回false会停止上传
            },
            // 上传成功
            handleSuccess(res, file) {
                if(this.novelUrl){
                    const data = {url:"/novel" + this.novelUrl}
                    removeMediaFile(data)
                    this.novelUrl = ''
                }
                this.novelFileName = res.data
                this.submitForm.mediaPath = this.novelFileName
            },
            // 获取文件名
            getFileName(path) {
                return path.split('/').pop();
            },
            // 下载文件
            downloadFile() {
                 const link = document.createElement('a');
                link.href = "http://127.0.0.1:9093/media/novel" + this.novelUrl;
                link.download = this.getFileName(this.novelUrl); 
                link.click();
            },
            // 删除文件处理
            handleRemove() {
                this.$confirm('确定要删除这个文件吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const data = {url:"/novel" + this.novelUrl}
                    removeMediaFile(data)
                    this.novelUrl = ''
                    this.submitForm.mediaPath = '';
                }).catch(() => {});
            }
        }
    }
</script>

<style scoped>
    .el-form-item{
        margin: 10px;
    }
    .address-form .el-select .el-input {
        border-color: #409EFF;
        width: 50px;
    }
    .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 20px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .cover-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .cover {
    width: 120px;
    height: 180px;
    border-radius: 20px;
    display: block;
  }
  
.boxCardUploadImg {
  width: 120px;
  height: 180px;
  border-radius: 20px;
  position: relative;
}
.boxCardUploadImg:hover {
  cursor: pointer;
}
.boxCardUploadImg:hover::after {
  content: '';
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 0;
  height: 100%;
  top: 0px;
  width: 100%;
  z-index: 99;
  border-radius: 20px;
}

.boxCardUploadImg i {
  display: none;
}
.boxCardUploadImg:hover i {
  position: absolute;
  font-size: 48px;
  display: initial;
  z-index: 999;
  color: #fff;
  top: 65px;
  left: 34px;
}
/* 两行省略 + hover 显示全部 */
.text-ellipsis-multi {
  display: -webkit-box;
  -webkit-line-clamp: 3;  /* 限制行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: 4.5em;  /* 2行 x 1.5行高 */
  cursor: pointer;
}

/* 调整 tooltip 最大宽度 */
.el-tooltip__popper {
  max-width: 400px;
  word-break: break-word;
}
</style>